import {movingAverage as average} from './MA'
/**
 * MACD配置参数
 */
let initParam = {
  name: 'MACD',
  type: 'polyline',
  caculateParam: [12, 26, 9]  // K线MA默认显示5，10，20，60天简单平均
}

/**
 * Caculator 数据处理
 *
 */
/**
 * Caculator 数据处理
 * @param  {array} rawData
 * @param  {array} caculateParam
 * @return {array} 二维数组
 * type 'close' => MACD ／ 'volume' => VMACD
 */

function caculate (rawData, caculateParam, type) {
  if (!(rawData instanceof Array && caculateParam instanceof Array)) throw new Error('Data or caculateParam is not Array')
  let mathData = []
  rawData.forEach((d, i) => {
    mathData.push(d)
  })
  return MACD(mathData, type, caculateParam[0], caculateParam[1], caculateParam[2])
}
// type = close: MACD; type = volume: VMACD;
function MACD (data, type, tShort, tLong, N) {
  let shortEMA = [data[0][type]]
  let longEMA = [...shortEMA]
  let MACD = [{time: data[0].time, value: 0}]
  let DIF = [{time: data[0].time, value: 0}]
  let DEA = [{time: data[0].time, value: 0}]

  for (let i = 1; i < data.length; i++) {
    shortEMA.push(shortEMA[i - 1] * (tShort - 1) / (tShort + 1) + data[i][type] * 2 / (tShort + 1))
    longEMA.push(longEMA[i - 1] * (tLong - 1) / (tLong + 1) + data[i][type] * 2 / (tLong + 1))
    let tempDIF = shortEMA[i] - longEMA[i]
    let tempDEA = DEA[i - 1].value * (N - 1) / (N + 1) + tempDIF * 2 / (N + 1)
    DIF.push({time: data[i].time, value: tempDIF})
    DEA.push({time: data[i].time, value: tempDEA})
    MACD.push({time: data[i].time, value: 2 * (DIF[i].value - DEA[i].value)})
  }
  return [MACD, DIF, DEA]
}

export default {
  initParam: initParam,
  caculate: caculate
}
